const path = require('path');
const {
  openBrowser,
  getWeCodeConfig,
  saveJsonFile,
  processSendError,
  checkPortVaild
} = require('../config/utils');
const fs = require('fs');
const { log } = require('../../log');

function start(processMessage) {

  process.env.NODE_ENV = 'development';
  process.env.WECODE_ENV = 'development';
  process.env.WEOCDE_PROCESS_MESSAGE = JSON.stringify(processMessage);

  const {
    env = {}
  } = processMessage;
  const {
    WECODE_APP_PATH,
    WECODE_ESLINT_PATH,
    WECODE_BOOTSTRAP_PATH, // asar 补丁文件
    WECODE_JSAPI_ASAR_PATH, // jsapi asar包,供本地调试用
    RUNTIME_PATH
  } = env;

  if (WECODE_APP_PATH === undefined || WECODE_APP_PATH === null) {
    log(chalk.red('Please set process env WECODE_APP_PATH!'));
    return;
  }
  
  process.env.WECODE_JSAPI_ASAR_PATH = WECODE_JSAPI_ASAR_PATH;
  process.env.WECODE_ESLINT_PATH = WECODE_ESLINT_PATH;
  // 设置环境变量，供webpack使用
  process.env.WECODE_APP_PATH = WECODE_APP_PATH;
  process.env.RUNTIME_PATH = RUNTIME_PATH || path.join(process.cwd(), '..');

  const chalk = require('chalk');
  const Service = require('@vue/cli-service');

  const runtimePath = path.join(__dirname, '..');
  const service = new Service(runtimePath);

  const appPath = WECODE_APP_PATH;

  // 获取 wecode.json 文件配置
  const { wecodeJson, wecodeFilePath } = getWeCodeConfig(appPath);

  process.env.ESLINT = wecodeJson.eslint;
  const {
    open,
    port
  } = wecodeJson.devServer;

  checkPortVaild(port);

  process.env.OPENBROWSER = open;

  const paths = require('../config/paths'); // 需要在设置  process.env.WECODE_APP_PATH 和  process.env.OPENBROWSER  之后再引入

  delete require.cache[require.resolve('../vue.config.js')];
  return service
    .run('serve')
    .then((data) => {
      const serverURL = new URL(data.url);
      checkPortVaild(serverURL.port);
      if (serverURL.port != port) {
        saveJsonFile(wecodeFilePath, {
          port: serverURL.port
        });
      }

      const browswerPath = `${data.url}${paths.baseURL}`;
      if (process && process.send) {
        process.send({
          status: 'done',
          request: processMessage,
          browserPath: open ? '' : browswerPath
        });
      }
      if (open) {
        openBrowser(browswerPath);
      }
      return;
    })
    .catch((error) => {
      log('编译出错！', error)
      processSendError(error);
      return error;
    });
}

process.on('unhandledRejection', err => {
  processSendError(err);
  throw err;
});

['SIGINT', 'SIGTERM'].forEach(function (sig) {
  process.on(sig, function () {
    process.exit();
  });
});

process.on('message', _data => {
  try {
    const data = JSON.parse(_data);
    const {
      cmd
    } = data;
    if (cmd === 'start') {
      start(data);
    }
  } catch (error) {
    log(error);
  }
});

module.exports = start;
